<?php

namespace app\api\model;

use app\common\model\BaseModel;
use think\model\concern\SoftDelete;

class Notice extends BaseModel
{

    use SoftDelete;

    

    // 表名
    protected $name = 'notice';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = 'deletetime';

    // 追加属性
    protected $append = [

    ];

    /**
     * 公告列表
     */
    public function noticeList($requestData, $user){
        $page = $requestData['page']??1;
        $limit = $requestData['limit']??10;
        $has_read = $user['notice_ids'] ? explode(',', $user['notice_ids']) : [];
        $list = self::field('id,title,intro,content,createtime')->where(['is_delete' => 1, 'status' => 1])->order('createtime', 'desc')->page($page, $limit)->select()->toArray();
        if($list){
            foreach ($list as $key=>$value){
                $list[$key]['createtime'] = date('Y-m-d H:i:s', $value['createtime']);
                if(in_array($value['id'], $has_read)){
                    $list[$key]['read'] = 2;
                }else{
                    $list[$key]['read'] = 1;
                }
            }
        }
        return $list;
    }

    /**
     * 公告详情
     */
    public function noticeDetails($requestData, $user){
        $id = $requestData['id']??0;
        $data = self::field('id,title,intro,content,createtime')->where(['is_delete' => 1, 'status' => 1, 'id' => $id])->find();
        if(!$id || !$data){
            return ['status' => 0, 'message' => '公告不存在', 'result' => ''];
        }
        $notice_ids = $user['notice_ids'];
        $notice_ids = $notice_ids ? explode(',', $notice_ids) : [];
        if(!in_array($id, $notice_ids)){
            array_push($notice_ids, $id);
        }
        $notice_ids = implode(',', $notice_ids);
        Merchant::where('id', $user['id'])->update(['notice_ids' => $notice_ids]);
        $data['createtime'] = date('Y-m-d H:i:s', $data['createtime']);
        return ['status' => 1, 'message' => '请求成功', 'result' => $data];
    }
    

    //公告信息
    public static function noticeInfo($merchant){
        $in_read = $merchant['notice_ids'] ? count(explode(',', $merchant['notice_ids'])) : 0;
        $all_notice = self::where(['is_delete' => 1, 'status' => 1])->count();
        $un_read = bcsub($all_notice, $in_read, 0);
        $last_notice = self::field('id,title')->where(['is_delete' => 1, 'status' => 1])->order('createtime', 'desc')->value('title');
        $data = [
            'un_read' => $un_read,
            'last_notice' => $last_notice
        ];
        return $data;
    }







}
